package com.gzist.elderlyserviceplatform.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzist.elderlyserviceplatform.entity.dto.ElderlyInfoDto;
import com.gzist.elderlyserviceplatform.entity.po.ElderlyInfo;
import com.gzist.elderlyserviceplatform.mapper.ElderlyInfoMapper;
import com.gzist.elderlyserviceplatform.service.ElderlyInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 家庭老人信息表 服务实现类
 */
@Service
public class ElderlyInfoServiceImpl extends ServiceImpl<ElderlyInfoMapper, ElderlyInfo> implements ElderlyInfoService {

    public boolean saveElderly(ElderlyInfo elderlyInfo){
        elderlyInfo.setCaretakerId(StpUtil.getLoginIdAsString());
       return  this.save(elderlyInfo);
    }

    @Override
    public void update(ElderlyInfo elderlyInfo) {
        LambdaUpdateWrapper<ElderlyInfo> wrapper =new LambdaUpdateWrapper();
              wrapper.eq(ElderlyInfo::getId,elderlyInfo.getId());
              this.update(elderlyInfo,wrapper);
    }

    @Override
    public Page<ElderlyInfo> cgetById(String id, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<ElderlyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElderlyInfo::getCaretakerId,id);
        return this.page(new Page<>(pageNum,pageSize),wrapper);
    }

    @Override
    public Page<ElderlyInfo> queryList(ElderlyInfoDto elderlyInfoDto) {
        LambdaQueryWrapper<ElderlyInfo> wrapper =new LambdaQueryWrapper<>();
            wrapper.eq(ElderlyInfo::getCaretakerId, StpUtil.getLoginIdAsString());
            wrapper.like(ElderlyInfo::getElderlyName,elderlyInfoDto.getElderlyName());
            return this.page(new Page<>(elderlyInfoDto.getPageNum(),elderlyInfoDto.getPageSize()),wrapper);
    }

    public Integer getAverageAge(){


        LambdaQueryWrapper<ElderlyInfo> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(ElderlyInfo::getCaretakerId, StpUtil.getLoginIdAsString());
        List<ElderlyInfo> elderlyInfos = this.list(wrapper);
        //默认65年龄
        if(elderlyInfos.size() == 0) {return 65;}


        //获取年龄平均值
        int sum = 0;
        for (ElderlyInfo elderlyInfo : elderlyInfos) {
            sum += elderlyInfo.getAge();
        }

        return sum/elderlyInfos.size();

    }


}
